﻿using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using WholeSlideImageLibrary.Core;

namespace WholeSlideImageLibrary
{
    public sealed class PhysicalFileSource : FileSourceInfo, IPhysicalFileSource
    {
        private readonly FileInfo _fileInfo;

        public override string? FileName => _fileInfo.Name;

        public override long FileSize => _fileInfo.Length;

        public string PhysicalFilePath => _fileInfo.FullName;

        public PhysicalFileSource(string fileName)
        {
            if (fileName is null)
            {
                throw new ArgumentNullException(nameof(fileName));
            }

            var info = new FileInfo(fileName);
            if (!info.Exists)
            {
                throw new FileNotFoundException();
            }

            _fileInfo = info;
        }

        public PhysicalFileSource(FileInfo fileInfo)
        {
            if (fileInfo is null)
            {
                throw new ArgumentNullException(nameof(fileInfo));
            }

            if (!fileInfo.Exists)
            {
                throw new FileNotFoundException();
            }

            _fileInfo = fileInfo;
        }

        public override ValueTask<FileSourceReader> OpenAsync(CancellationToken cancellationToken = default)
        {
            return new ValueTask<FileSourceReader>(new PhysicalFileReader(_fileInfo.FullName));
        }

        public override ValueTask<DirectorySourceInfo?> GetContainingDirectoryAsync(CancellationToken cancellationToken = default)
        {
            return new ValueTask<DirectorySourceInfo?>(new PhysicalDirectorySource(_fileInfo.Directory));
        }

    }
}
